package com.huilian.iotbox.admin.consumer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huilian.iotbox.admin.config.DelayMQConfig;
import com.huilian.iotbox.admin.service.*;
import com.huilian.iotbox.data.cmd.PositiveDataFrameCMD;
import com.huilian.iotbox.aliyun.service.PubService;
import com.huilian.iotbox.data.enums.CompositeDelayQueueEnum;
import com.huilian.iotbox.data.po.*;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * MQ处理处理任务类
 *
 * @author: 少凡
 * @Date 2018/11/25 15:56
 */
@Component
@Slf4j
public class RabbitReceiver {

    @Value("${huilian.iot.productKey}")
    private String productKey;
    @Autowired
    private PubService pubService;
    @Autowired
    LogLoginService logLoginService;
    @Autowired
    private MessageLogService messageLogService;
    @Autowired
    private MemberStoreBalanceService memberStoreBalanceService;


    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "${spring.rabbitmq.listener.iotBoxLogLogin.queue.name}",

            durable = "${spring.rabbitmq.listener.iotBoxLogLogin.queue.durable}"),
            exchange = @Exchange(value = "${spring.rabbitmq.listener.iotBoxLogLogin.exchange.name}",
                    durable = "${spring.rabbitmq.listener.iotBoxLogLogin.exchange.durable}",
                    type = "${spring.rabbitmq.listener.iotBoxLogLogin.exchange.type}"),
            ignoreDeclarationExceptions = "${spring.rabbitmq.listener.iotBoxLogLogin.exchange.ignoreDeclarationExceptions}",
            key = "iotBoxLogLogin"))
    @RabbitHandler
    public void recordRequestLog(@Payload String json, Channel channel, @Headers Map<String, Object> headers) throws IOException {
        LogLogin logLogin = JSON.parseObject(json, LogLogin.class);
        log.info("--------收到MQ--------时间：" + DateTimeUtils.format(logLogin.getCreateTime()) + ",请求ip地址：" + logLogin.getIp());
        try {
            logLoginService.insert(logLogin);
        } catch (Exception e) {
            log.error("--------收到MQ--------时间：" + DateTimeUtils.format(logLogin.getCreateTime()) + ",请求ip地址：" + logLogin.getIp());
        } finally {
            Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            //手工ACK
            channel.basicAck(deliveryTag, true);
        }
    }

    /**
     * 监听接收到延迟队列消息
     *
     * @param map
     * @param channel
     * @param headers
     * @throws IOException
     */
    @RabbitListener(queues = DelayMQConfig.IOT_BOX_ADMIN_LAZY_QUEUE)
    @RabbitHandler
    public void onReplayLazyQueue(@Payload Map<String, String> map, Channel channel, @Headers Map<String, Object> headers) throws IOException {
        try {
            String code = map.get("code");
            if (CompositeDelayQueueEnum.INITIATIVE_SEND_QUERY_BASE_PARAMS.getCode().equals(code)) {
                // 主动通过串口去查设备的参数
                String tcp = PositiveDataFrameCMD.queryBaseParams();
                log.info("tcp:" + tcp);
                String penetrate = PositiveDataFrameCMD.penetrate(tcp);
                pubService.pub(penetrate, map.get("deviceNo"), productKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            //手工ACK
            channel.basicAck(deliveryTag, true);
        }

    }


    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "${spring.rabbitmq.listener.messageLog.queue.name}",
            durable = "${spring.rabbitmq.listener.messageLog.queue.durable}"),
            exchange = @Exchange(value = "${spring.rabbitmq.listener.messageLog.exchange.name}",
                    durable = "${spring.rabbitmq.listener.messageLog.exchange.durable}",
                    type = "${spring.rabbitmq.listener.messageLog.exchange.type}"),
            ignoreDeclarationExceptions = "${spring.rabbitmq.listener.messageLog.exchange.ignoreDeclarationExceptions}",
            key = "${spring.rabbitmq.listener.messageLog.key}"))
    @RabbitHandler
    public void messageLog(@Payload String json, Channel channel, @Headers Map<String, Object> headers) throws IOException {
        MessageLog messageLog = JSON.parseObject(json, MessageLog.class);
        try {
            messageLogService.insert(messageLog);
        } catch (Exception e) {
            log.error("消息插入异常：{}", e.getMessage());
        } finally {
            Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            //手工ACK
            channel.basicAck(deliveryTag, true);
        }
    }

}
